﻿using System;
using System.Collections.Generic;
using System.Web.Mvc;
using Gfw.BLL.Basic.User;
using Gfw.Infrastructure.ExceptionImpl;
using Gfw.Web.Common;
using Gfw.Web.Models.Genealogy;

namespace Gfw.Web.Controllers
{
    public class UserGenealogyController : Controller
    {
        private const int PageSize = 10;
        private const string PAGEINDEX = "PageIndex";

        public string RootCode
        {
            get { return Session["UserGenealogyController_RootCode"].ConvertTo<string>(null); }
            set { Session["UserGenealogyController_RootCode"] = value; }
        }

        public int TotalPage
        {
            get { return Session["UserGenealogyController_TotalPage"].ConvertTo<int>(0); }
            set { Session["UserGenealogyController_TotalPage"] = value; }
        }

        #region 会员结构图

        /// <summary>
        /// 通过制定用户的顺序号，来完成会员结构图的绘制
        /// </summary>
        /// <param name="u">用户的登录名称</param>
        /// <param name="type">主要是用户添加用户以后，返回该页面</param>
        /// <returns></returns>
      
       [SecurityVerify(Order = 1)]
        [LAuthorize]
        public ActionResult Index1(string u, string type)
        {
            try
            {
                if (type != null && type.Equals("goback", StringComparison.CurrentCultureIgnoreCase))
                    return View();
                u = u ?? L.Manage.Authentication.Context.CurrentUser.LoginName;
                string code;
                TotalPage = (UserGenealogyLogic.GetChildrenCount(u, out code) + PageSize - 1) / PageSize;
                if (!code.StartsWith(L.Manage.Authentication.Context.CurrentUser.Code))
                    throw new GfwException("您查询的用户，已经超出范围！");
                RootCode = code;
                ViewBag.RootUser = u;
                return View();
            }
            catch (Exception exp)
            {
                ModelState.AddModelError("", "您所查询的用户不在你的下级节点中!");
                return View();
            }
        }



        /// <summary>
        /// 显示会员结构图列表
        /// </summary>
        /// <param name="page"></param>
        /// <returns></returns>
        [OutputCache(Duration = 1)]
        [LAuthorize]
        public ActionResult List(int? page)
        {
            var p = page ?? 1;
            ViewBag.PageIndex = p;
            ViewBag.TotalPage = TotalPage;

            var list = UserGenealogyLogic.GetGenealogy(RootCode, p - 1, 10);
            return PartialView(list);
        }


        /// <summary>
        /// 我的会员结构图
        /// </summary>
        /// <returns></returns>
        [LAuthorize]
        public ActionResult My()
        {
            return RedirectToAction("Index1");
        }

        /// <summary>
        /// 上层会员结构图
        /// </summary>
        /// <returns></returns>
        [LAuthorize]
        public ActionResult Up()
        {
            if (RootCode != null)
            {
                var code = RootCode.Substring(0, RootCode.Length - 1);
                string u = string.IsNullOrEmpty(code) ? null : UserLogic.GerLoginName(code);
                return RedirectToAction("Index1", new { u = u });
            }
            else
            {
                return RedirectToAction("Index1", new { u = "0" });
            }

        }

        #endregion

        #region 查询推荐会员

        /// <summary>
        /// 我所推荐的会员统计
        /// </summary>
        /// <returns></returns>
        [SecurityVerify]
        [LAuthorize]
        public ActionResult RecommendMembersCount()
        {
            string recommenderID = L.Manage.Authentication.Context.CurrentUser.Id;
            string recommenderCode = L.Manage.Authentication.Context.CurrentUser.Code;

            if (string.IsNullOrEmpty(recommenderID) || string.IsNullOrEmpty(recommenderCode))
            {
                return HttpNotFound();
            }

            long leftChildrenCount, rightChildrenCount;
            UserLogic.GetRecommendMembersCount(recommenderID, recommenderCode, out leftChildrenCount, out rightChildrenCount);

            ViewBag.LeftCount = leftChildrenCount;
            ViewBag.RightCount = rightChildrenCount;

            return View();
        }

        /// <summary>
        /// 我所推荐的会员列表
        /// </summary>
        /// <param name="page">从第一页开始计算</param>
        /// <returns></returns>
        [LAuthorize]
        public ActionResult RecommendMembersList(int? page)
        {
            try
            {
                // 这里使用 TempDate 不使用 Session 的原因：
                // 是弹窗，不是网页之间的切换。
                // 若是网页之间的切换，就要用 Session，比如看完详情后，要返回到该 Page 页上。
                // 也可以参考前台广告更多的详情方法。
                if (TempData[PAGEINDEX] == null)
                    TempData[PAGEINDEX] = 1;

                int totalSize, index = page ?? (int)TempData[PAGEINDEX];
                string userID = L.Manage.Authentication.Context.CurrentUser.Id;
                if (index < 1)
                    index = 1;
                
                if (!string.IsNullOrEmpty(userID))
                {
                    IList<UserRecommendMemberModel> list = UserLogic.GetUserRecommendMembersInfo(userID, index - 1,ViewHelper.PageSize,out totalSize);
                    ViewBag.TotalSize = totalSize;
                    TempData[PAGEINDEX] = ViewBag.PageIndex = index;

                    return PartialView(list);
                }
                else
                    return HttpNotFound();
            }
            catch (System.Exception ex)
            {
                return HttpNotFound(ex.Message);
            }
        }


        /// <summary>
        /// 详情
        /// </summary>
        /// <param name="userID">用户ID</param>
        /// <param name="recommenderCode">推荐人Code</param>
        /// <returns></returns>
        [LAuthorize]
        public ActionResult Details(string userID, string recommenderCode)
        {
            UserRecommendMemberModel model = UserLogic.GetUserRecommendMemberInfoByUserID(userID, recommenderCode);
            if (model == null)
                return HttpNotFound();

            return View(model);
        }

        #endregion
    }
}
